/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time: string | number | Date, cFormat: string) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: any = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  return format.replace(
    /{([ymdhisa])+}/g,
    (result: string | any[], key: string) => {
      let value = formatObj[key]
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value]
      }
      if (result.length > 0 && value < 10) {
        value = `0${value}`
      }
      return value || 0
    }
  )
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source: any) {
  if (!source && typeof source !== 'object') {
    // @ts-ignore
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj: any = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function getKeys(str: string) {
  const reg = /\$\{(.+?)\}/
  const reg_g = /\$\{(.+?)\}/g
  const result: any = str.match(reg_g)
  if (!result) {
    return []
  }
  const list = []
  for (let i = 0; i < result.length; i++) {
    const item = result[i]
    list.push(item.match(reg)[1])
  }
  return list
}
/**
 * @description 驼峰转-连接
 * @param str
 * @returns
 */
export function handler(str: string) {
  let tuo = ''
  const arr = str.split('')
  const newArr = arr.map(ite => {
    return ite.toUpperCase() === ite ? (ite = '-' + ite.toLowerCase()) : ite
  })
  tuo = newArr.join('')
  return tuo
}
/**
 * @description 横线转驼峰
 * @param str
 * @returns str
 */
export function dashToCamelCase(str: string): string {
  return str.replace(/-(\w)/g, (match, p1) => p1.toUpperCase())
}

/**
 * @description 驼峰转横线
 * @param str
 * @returns str
 */
export function camelToDash(str: string): string {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

/**
 * @description 获取mp3时长
 * @param url
 * @returns Promise<number>
 * @date 2020-04-23
 */
export function getMP3Length(url: string): Promise<number> {
  return new Promise((rel: any) => {
    const audioContext = new (window.AudioContext ||
      window.webkitAudioContext)()
    fetch(url)
      .then(response => response.arrayBuffer())
      .then(buffer => audioContext.decodeAudioData(buffer))
      .then(audioBuffer => {
        const duration = audioBuffer.duration
        rel(duration)
      })
      .catch(error => {
        console.error('获取MP3长度失败：', error)
      })
  })
}

/**
 * @description 时长格式转换
 * @param musicTime
 * @returns string
 * @date 2020-04-23
 */
export function formatMusicTime(musicTime: number) {
  const branch = Math.floor(musicTime / 60)
  const second = Math.floor(musicTime % 60)
  if (branch < 10 && second < 10) {
    return `0${branch}:0${second}`
  } else if (branch < 10) {
    return `0${branch}:${second}`
  } else if (second < 10) {
    return `${branch}:0${second}`
  } else {
    return `${branch}:${second}`
  }
}

/**
 * @description 一维数组转换为二维数组
 * @param data
 * @param rowLength
 * @returns array
 * @date 2024-01-30
 */
export function convertTo2DArray<T>(data: T[], rowLength: number): T[][] {
  const result: T[][] = []
  const dataLength = data.length

  for (let i = 0; i < dataLength; i += rowLength) {
    const row = data.slice(i, i + rowLength)
    result.push(row)
  }
  return result
}
